package com.online.music.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.online.music.common.MessageConstant;
import com.online.music.entity.enums.UserRole;
import com.online.music.entity.po.User;
import com.online.music.entity.vo.UserVo;
import com.online.music.mapper.UserMapper;
import com.online.music.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.online.music.utils.UserContextUtil;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;

import java.util.List;

import com.online.music.common.Result;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: Leno
 * @Date: 2025-01-31
 * @Description: UserServiceImpl
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;

    @Override
    public Result<Page<User>> findPage(Integer pageNum, Integer pageSize, User user) {
        Page<User> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        return Result.success(page(page, lqw));
    }

    @Override
    @Transactional
    public Result<String> deleteBatch(List<Long> ids) {
        // 删除前先判断是否存在...
        removeByIds(ids);
        return Result.successMsg("删除成功");
    }

    @Override
    public Result<UserVo> login(User user) {
        // 查询是否存在
        User dbUser = lambdaQuery()
                .eq(User::getUsername, user.getUsername())
                .or()
                .eq(User::getEmail, user.getUsername())
                .one();
        if (dbUser == null) {
            return Result.error(MessageConstant.USERNAME_NOT_EXIST);
        }
        // 判断是否被封禁
        if (dbUser.getStatus() == 0) {
            return Result.error(MessageConstant.USER_DISABLED);
        }
        // 判断密码是否正确
        if (!dbUser.getPassword().equals(user.getPassword())) {
            return Result.error(MessageConstant.LOGIN_FAIL);
        }
        StpUtil.login(dbUser.getId());
        UserVo userVo = new UserVo();
        BeanUtil.copyProperties(dbUser, userVo);
        userVo.setToken(StpUtil.getTokenValue());
        return Result.successDataAndMeg(userVo, MessageConstant.LOGIN_SUCCESS);
    }

    @Override
    public Result<String> register(User user) {
        user.setCreateTime(null);
        user.setUpdateTime(null);
        user.setRole(UserRole.USER);
        save(user);
        return Result.successMsg(MessageConstant.REGISTER_SUCCESS);
    }


}

